package com.ebelter.seneo.models;


import com.ebelter.btcomlib.models.beans.UpdateVersionBean;
import com.ebelter.btcomlib.models.https.BaseJsonGenerator;
import com.ebelter.btcomlib.models.https.HttpsUrl;
import com.ebelter.btcomlib.models.https.MyStringCallback;
import com.ebelter.btcomlib.models.https.interfaces.HttpResponse;
import com.ebelter.btcomlib.models.https.responses.BaseResponse;
import com.ebelter.btcomlib.models.https.responses.LoginResponse;
import com.ebelter.btcomlib.models.https.responses.LoginResponseSubInfo;
import com.ebelter.btcomlib.models.https.responses.RegisterResponse;
import com.ebelter.btcomlib.utils.GsonUtils;
import com.ebelter.btcomlib.utils.log.LogUtils;
import com.ebelter.seneo.beans.HostoryListData;
import com.ebelter.seneo.beans.httpresponse.AddChildrenRS;
import com.ebelter.seneo.beans.httpresponse.GetAverageResponse;
import com.ebelter.seneo.beans.httpresponse.OriginalParametersResponse;
import com.ebelter.seneo.models.updateApp.UpdateService;
import com.ebelter.seneo.utils.SeneoUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpHeaders;
import com.lzy.okgo.model.HttpParams;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Response;


//网络工具
public class SeneoNet {

    public static final boolean outputLog = false;
    public static final String TAG = "SeneoNet";
    private static SeneoNet intance;

    public static SeneoNet getIntance() {
        if (intance==null){
            synchronized (SeneoNet.class){
                intance = new SeneoNet();
            }
        }
        return intance;
    }
    private BaseJsonGenerator mBaseJsonGenerator;

    public SeneoNet() {
        mBaseJsonGenerator=new BaseJsonGenerator();
    }

    private void outLog(String msg){
        if (outputLog){
            LogUtils.i(TAG,msg);
        }
    }


    /**
     * 注册用户
     * @param type type=1 注册 type=2 忘记密码
     */
    public void registerRequest(Object tag,long mainId, String nickName,String email,String password,String birthday,
                                int height, int sex,int profession,int type,
                                final HttpResponse<RegisterResponse> httpResponse){
        String registerjson=mBaseJsonGenerator.getRegisterRJ2(mainId,nickName, email, password,birthday,height,sex,profession, type);
        outLog("注册Json："+registerjson);
        postJson(tag, HttpsUrl.registerUrlNoEmail,registerjson ,
                new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        RegisterResponse res= GsonUtils.getInstance().fromJson(s,RegisterResponse.class);
                        if (res!=null){
                            httpResponse.result(true,R_S_R_S,res,s);
                        }else {
                            httpResponse.result(false,R_S_R_F,null,null);
                        }
                    }
                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        httpResponse.result(false,R_F,null,null);
                    }
                }
        );
    }


    /**
     * 注册用户
     * @param type type=1 注册 type=2 忘记密码
     */
    public void registerChildrenRequest(Object tag,long mainId, String nickName,String birthday,
                                int height, int sex,int profession,int type,
                                final HttpResponse<AddChildrenRS> httpResponse){
        String registerjson=mBaseJsonGenerator.getRegisterRJ2(mainId,nickName, null, null,birthday,height,sex,profession, type);
        outLog("注册子账号Json："+registerjson);
        postJson(tag, HttpsUrl.addChildren,registerjson ,
                new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        AddChildrenRS res= GsonUtils.getInstance().fromJson(s,AddChildrenRS.class);
                        if (res!=null){
                            httpResponse.result(true,R_S_R_S,res,s);
                        }else {
                            httpResponse.result(false,R_S_R_F,null,null);
                        }
                    }
                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        httpResponse.result(false,R_F,null,null);
                    }
                }
        );
    }


    /**
     *
     * 登录请求
     * @param isLoginEmail 是否是邮箱登录
     * @param loginStr 登录的字符串
     * @param psw MD5加密的密码
     * @param httpResponse 返回请求
     */
    public void loginRequest(Object tag, boolean isLoginEmail, String loginStr, String psw,
                             final HttpResponse<LoginResponseSubInfo> httpResponse){
        String loginRJ=mBaseJsonGenerator.getLoginRJ(isLoginEmail,loginStr,psw);
        outLog("登录的json："+loginRJ);
        postJson(tag,HttpsUrl.loginUrl2,loginRJ,
                new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        LoginResponseSubInfo res=GsonUtils.getInstance().fromJson(s,LoginResponseSubInfo.class);
                        if (res!=null){
                            httpResponse.result(true,R_S_R_S,res,s);
                        }else {
                            httpResponse.result(false,R_S_R_F,null,null);
                        }
                    }
                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        httpResponse.result(false,R_F,null,null);
                    }
                }
        );
    }




    //更新密码
    public void findPassWord(Object tag, String email, String newPassword, String code, final HttpResponse<BaseResponse> httpResponse){
        // paramMap.put(HttpsParameters.USER_ID, UserSpUtil.readLong(Constants.IUser.USER_ID));
        Map<String,Serializable> paramMap=new HashMap<>();
        paramMap.put("email",email);
        paramMap.put("newPassword",newPassword);
        paramMap.put("code",code);
        postJson(tag, HttpsUrl.updatePasswordUrl, mBaseJsonGenerator.getMapRJ(paramMap), new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {

                BaseResponse res=GsonUtils.getInstance().fromJson(s,BaseResponse.class);
                if (res!=null){
                    httpResponse.result(true,R_S_R_S,res,s);
                }else {
                    httpResponse.result(false,R_S_R_F,null,null);
                }
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                httpResponse.result(false,R_F,null,null);
            }

        });
    }




    //"userId":"2af7b9c6139d4d5bbd960d503ad064b7", 这个字段必不可少
    public void setTargetWeight(Object tag, final Map<String,Serializable> paramMap, final HttpResponse<OriginalParametersResponse> httpResponse){
        postJson(tag,HttpsUrl.setTargetWeight,mBaseJsonGenerator.getMapRJ(paramMap),
                new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        OriginalParametersResponse res = GsonUtils.getInstance().fromJson(s,OriginalParametersResponse.class);
                        if (res!=null){
                            res.originalParameters=paramMap;
                            httpResponse.result(true,R_S_R_S,res,s);
                        }else {
                            httpResponse.result(false,R_S_R_F,null,s);
                        }
                    }
                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        httpResponse.result(false,R_F,null,null);
                    }
                }
        );
    }


    //上传用户数据
    //"userId":"2af7b9c6139d4d5bbd960d503ad064b7", 这个字段必不可少
    public void uploadData(Object tag, final Map<String,Serializable> paramMap,
                           final HttpResponse<OriginalParametersResponse> httpResponse){
        postJson(tag,HttpsUrl.uploadData,mBaseJsonGenerator.getMapRJ(paramMap),

                new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        OriginalParametersResponse res = GsonUtils.getInstance().fromJson(s,OriginalParametersResponse.class);
                        if (res!=null){
                            res.originalParameters=paramMap;
                            httpResponse.result(true,R_S_R_S,res,s);
                        }else {
                            httpResponse.result(false,R_S_R_F,null,s);
                        }
                    }
                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        httpResponse.result(false,R_F,null,null);
                    }
                }
        );
    }




    //获取测量的数据


    //获取平均数 whichTime 1天2周3月  趋势界面
    public void getsAverageData(Object tag,int whichTime,final Map<String,Serializable> paramMap, final HttpResponse<GetAverageResponse> httpResponse){

        final String url;
        if (whichTime==1){
            url=HttpsUrl.getsAverageDay;
        }else if (whichTime==2){
            url=HttpsUrl.getsAverageWeek;
        }else if (whichTime==3){
            url=HttpsUrl.getsAverageMonth;
        }else {
            return;
        }


        postJson(tag, url, mBaseJsonGenerator.getMapRJ(paramMap), new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                LogUtils.i(TAG,"---getsAverageData---onSuccess()--"+s);
                GetAverageResponse res = GsonUtils.getInstance().fromJson(s,GetAverageResponse.class);
                if (res!=null){
                    httpResponse.result(true,R_S_R_S,res,s);
                }else {
                    httpResponse.result(false,R_S_R_F,null,s);
                }

            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                e.printStackTrace();
                httpResponse.result(false,R_F,null,null);
            }
        });


    }


    public void getsHostoryListData(Object tag, Map<String,Serializable> paramMap, final HttpResponse<HostoryListData> httpResponse){
        postJson(tag, HttpsUrl.getHostoryDatas, mBaseJsonGenerator.getMapRJ(paramMap), new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                LogUtils.i2(TAG,"---getsHostoryListData---onSuccess()--"+s);
                HostoryListData hostoryListData=GsonUtils.getInstance().fromJson(s,HostoryListData.class);

                if (hostoryListData!=null){
                    httpResponse.result(true,R_S_R_S,hostoryListData,s);
                }else {
                    httpResponse.result(false,R_S_R_F,null,s);
                }

            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                e.printStackTrace();
                LogUtils.i(TAG,"---getsHostoryListData---onError()--");
                httpResponse.result(false,R_F,null,null);

            }
        });
    }

    public void deleteMeasureDataById(Object tag, String id, final HttpResponse<BaseResponse> httpResponse){
        String requestJson = "{\"id\":\""+id+"\"}";
        postJson(tag, HttpsUrl.deleteDatas, requestJson, new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                LogUtils.i(TAG,"---deleteMeasureDataById--"+s);
                BaseResponse baseResponse=GsonUtils.getInstance().fromJson(s,BaseResponse.class);

                if (baseResponse!=null){
                    httpResponse.result(true,R_S_R_S,baseResponse,s);
                }else {
                    httpResponse.result(false,R_S_R_F,null,s);
                }

            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                e.printStackTrace();
                LogUtils.i(TAG,"---getsHostoryListData---onError()--");
                httpResponse.result(false,R_F,null,null);

            }
        });
    }

    public void deleteUserById(Object tag, long userid, final HttpResponse<BaseResponse> httpResponse){
        String requestJson = "{\"userId\":\""+userid+"\"}";
        postJson(tag, HttpsUrl.deleteUser, requestJson, new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                LogUtils.i(TAG,"---deleteUserById--"+s);
                BaseResponse baseResponse=GsonUtils.getInstance().fromJson(s,BaseResponse.class);
                if (baseResponse!=null){
                    httpResponse.result(true,R_S_R_S,baseResponse,s);
                }else {
                    httpResponse.result(false,R_S_R_F,null,s);
                }

            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                e.printStackTrace();
                LogUtils.i(TAG,"---deleteUserById---onError()--");
                httpResponse.result(false,R_F,null,null);

            }
        });
    }


    //请求服务器上面的Version信息
    public void getVersionJosn(Object object,final HttpResponse<UpdateVersionBean> httpResponse){
        post(object, UpdateService.getVersionJson, new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                LogUtils.i(TAG,"服务器上的json数据："+s);
                UpdateVersionBean res= GsonUtils.getInstance().fromJson(s,UpdateVersionBean.class);
                if (res!=null){
                    httpResponse.result(true,"成功",res,s);
                }else {
                    httpResponse.result(false,"失败",null,s);
                }
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                httpResponse.result(false,"失败",null,"onError");
            }
        });
    }



    //更新用户信息
    public void updateInfo(Object tag,Map<String, Serializable> paramMap, HttpResponse<BaseResponse> httpResponse){
        String json=mBaseJsonGenerator.getMapRJ(paramMap);
        postJson(tag, HttpsUrl.updateInfoUrl, json, new MyStringCallback(httpResponse,BaseResponse.class));
    }


    /**
     * get请求获取数据
     */
    public <T> void get(Object tag, String url,StringCallback callback){
        OkGo.get(url).tag(tag).execute(callback);
    }

    public void getFileDownLoad(Object tag, String url, FileCallback fileCallback){
        OkGo.get(url).tag(tag).execute(fileCallback);
    }


    public void cancelTag(Object tag){
        OkGo.getInstance().cancelTag(tag);
    }
    /**
     * post请求获取数据
     */
    public void post(Object tag, String url, StringCallback callback){
        post(tag,url,null,callback);
    }
    /**
     * post请求获取数据
     */
    public  void post(Object tag, String url, HttpParams httpParams, StringCallback callback){
        OkGo.post(url).tag(tag).params(httpParams).execute(callback);
    }

    /**
     * postString请求获取数据
     */
    public void postString(Object tag, String url, String requestString, StringCallback callback){
        OkGo.post(url).tag(tag).upString(requestString).execute(callback);
    }
    /**
     * postJson请求获取数据
     */
    public void postJson(Object tag, String url, String requestJson, StringCallback callback){
        OkGo.post(url).tag(tag).upJson(requestJson).execute(callback);
    }

    //-----------------------------------------------------------------------------------------------------------------------------

    static final String  R_S_R_S = "请求成功,解析成功";
    static final String  R_S_R_F = "请求成功，解析失败";
    static final String  R_F = "请求失败";




    public  void post2(Object tag, String url, HttpHeaders headers, HttpParams httpParams, StringCallback callback){
        OkGo.post(url).tag(tag).headers(headers).params(httpParams).execute(callback);
    }







}
